﻿using System;
using System.Windows;
using System.Threading;
using Microsoft.Practices.Prism.PubSubEvents;
using Hopscotch.Application.Shell.Login;
using Hopscotch.Common.Logging;
using Hopscotch.Presentation.Configuration;

namespace Hopscotch.Application.Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : System.Windows.Application
    {       
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var logger = AppLogger.CreateLogger<App>();

            //Locally scoped mediator to send bootstrapper updates to login/splash window
            IEventAggregator eventAggregator = new EventAggregator();
            var loginInfo = ShowSplashScreen(eventAggregator);

            //Wait to be signaled that the login is done/cancelled             
            loginInfo.Signal.Wait();
            try
            {
                if (loginInfo.LoginSuccess)
                {
                    //NB: This must be run on the main application thread
                    var bootstrapper = new Bootstrapper(eventAggregator, loginInfo.Environment);
                    bootstrapper.Run();

                    //If the bootstrapper has run, close the splash
                    //loginViewModel.Close();
                    eventAggregator.GetEvent<SplashCloseEvent>().Publish(new SplashCloseEvent());
                }
                else
                {
                    this.Shutdown();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error OnStartup", ex);
                var messageUpdateEvent = eventAggregator.GetEvent<MessageUpdateEvent>();
                messageUpdateEvent.Publish(
                    new MessageUpdateEvent()
                    {
                        Message = ex.Message,
                        ErrorDetail = ex.ToString(),
                        IsError = true
                    });
            }
        }

        private LoginInfo ShowSplashScreen(IEventAggregator eventAggregator)
        {
            
            IEnvironmentsConfiguration environmentsConfiguration =
               (EnvironmentsConfigurationSection)System.Configuration.ConfigurationManager.GetSection(EnvironmentsConfigurationSection.SectionName);

            LoginInfo loginInfo = new LoginInfo();

            //Run the login/splash-screen on a seperate thread to maintain responsiveness
            var thread = new Thread(() =>
            {
                var wndw = new LoginDialog(eventAggregator, environmentsConfiguration, loginInfo);

                wndw.Show();
                wndw.Closed += (sender2, e2) =>
                    wndw.Dispatcher.InvokeShutdown();

                System.Windows.Threading.Dispatcher.Run();

            });
            thread.Name = typeof(LoginDialog).Name;
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();

            return loginInfo;
        }
    }
}
